package com.idea.relax.log.api.callback;

import com.idea.relax.log.support.CallbackMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.ObjectProvider;


/**
 * @author: 沉香
 * @date: 2022/12/27
 * @description: FailureCallback控制器,负责控制和决策FailureCallback的调用
 */
@Slf4j
public class RelaxFailureCallbackHandler {

    private final FailureCallback failureCallback;

    public RelaxFailureCallbackHandler(ObjectProvider<FailureCallback> objectProvider) {
        this.failureCallback = objectProvider.getIfAvailable();

    }

    public boolean callIfAvailable(CallbackMessage callbackMessage) {
        boolean called = false;
        if (failureCallback != null) {
            failureCallback.onFailure(callbackMessage);
            called = true;
        }
        return called;
    }

    public void onException(CallbackMessage callbackMessage) {
        log.error("Relax log task execution exception,thread name [" + Thread.currentThread().getName() + "]", callbackMessage.getThrowable());
        boolean called = callIfAvailable(callbackMessage);
        if (called) {
            log.info("The 'FailureCallback' is executed successfully.");
        } else {
            log.warn("'FailureCallback' is undefined, you can implement FailureCallback interface to define it.");
        }
    }

}
